/*****目标团队--靶标 --夺旗赛*****/
<template
  ><!---->
  <search-table
    ref="searchTable"
    :columns="targetTeamCol"
    :data="targetTeamData"
    :total="targetTeamTotal"
    :page.sync="queryTargetTeamInfo.pageIndex"
    :size.sync="queryTargetTeamInfo.pageSize"
    :disabled="
      (data) => {
        data.targetVisibility == 1
      }
    "
    showSelectTag
    :selection.sync="selectTargetTeams"
    @change-size="getTargetSize"
    @change-page="getTargetPage"
  >
    <Alert type="warning" show-icon slot="alert">
      <p style="color:#f90">未分配的题目禁止切换是否显示的状态</p>
    </Alert>
    <template slot="button-group">
      <Button
        ghost
        v-if="configMode !== 1"
        type="primary"
        :disabled="disabledAllBtn || progress == 4"
        title="添加题目"
        @click="showAddAndUpdate()"
        style="margin-right:15px;"
        >添加题目</Button
      >
      <Button
        ghost
        type="primary"
        :disabled="disBatchShowBtn() || targetAllotTotal < 1 || disabledAllBtn"
        @click="batchShow"
        style="margin-right:15px;"
        >批量显示</Button
      >
    </template>
    <template slot="select-group">
      <Select filterable
        v-model="queryTargetTeamInfo.isFixedFileFlag"
        placeholder="验证类型"
        @on-change="getTargetPage(1)"
        style="width:150px;margin-right:15px;"
        transfer
        clearable
      >
        <Option value="1">静态Flag</Option>
        <Option value="0">固定Flag</Option>
        <Option value="3">提交报告</Option>
      </Select>
      <Select filterable
        v-model="queryTargetTeamInfo.isNeedEnv"
        placeholder="是否需要环境"
        @on-change="getTargetPage(1)"
        clearable
        style="width:150px;margin-right:15px;"
      >
        <Option value="1">是</Option>
        <Option value="0">否</Option>
      </Select>
      <!-- <Select filterable //暂时不支持
        v-model="queryTargetTeamInfo.circumstance"
        placeholder="环境类型"
        @on-change="getTargetPage(1)"
        clearable
        style="width:150px;margin-right:15px;"
      >
        <Option value="share">共享环境</Option>
        <Option value="private">独享环境</Option>
      </Select> -->
      <Select filterable
        v-model="queryTargetTeamInfo.isNeedSubmitFlag"
        placeholder="是否需要提交Flag"
        @on-change="getTargetPage(1)"
        clearable
        style="width:150px;margin-right:15px;"
      >
        <Option value="1">是</Option>
        <Option value="0">否</Option>
      </Select>
      <Select filterable
        v-model="queryTargetTeamInfo.name"
        placeholder="请选择题目"
        @on-change="getTargetPage(1)"
        clearable
        style="width:150px;margin-right:15px;"
      >
        <Option
          v-for="item in allTargetTeamData"
          :value="item.name"
          :key="item.id"
          :title="item.name"
          >{{ item.name }}</Option
        >
      </Select>
    </template>
    <Modal
      v-model="targetModal.show"
      :title="targetModal.title"
      :loading="targetModal.loading"
      width="600px"
      :mask-closable="false"
      @on-cancel="handleReset()"
      @on-ok="saveTargetTeam"
    >
      <Form
        ref="formValidate"
        :model="formValidate"
        :rules="ruleValidate"
        :label-width="100"
        v-if="targetModal.type == '1'"
      >
        <Alert type="warning" show-icon v-if="needEnv == '1'">
          <p style="color:#f90">
            确认添加需要环境的题目后，系统将自动部署已选题目，并返回竞赛列表页面。
          </p>
        </Alert>
        <!-- envType === 0  共享环境,都是没有环境的题目-->
        <FormItem label="类型" prop="needEnv">
          <RadioGroup v-model="needEnv" @on-change="changeNeedEnv">
            <Radio
              label="1"
              :disabled="([2, 3, 5].includes(progress) && onlineMode == 1) || envType === 0"
              >需要环境</Radio
            >
            <Radio label="0">不需要环境</Radio>
          </RadioGroup>
        </FormItem>
        <!--          <FormItem label="题目" prop="id" v-if="needEnv == '1'">-->
        <!--            <Select filterable v-model="formValidate.id" placeholder="请选择题目" filterable>-->
        <!--              <Option  v-for="question in showQuestionList" :value="question.id"  :key="question.id">{{question.name}}</Option>-->
        <!--            </Select>-->
        <!--          </FormItem>-->
        <FormItem label="题目" prop="ids">
          <Select filterable v-model="formValidate.ids" placeholder="请选择题目" filterable multiple>
            <Option
              v-for="question in showQuestionList"
              :value="question.id"
              :key="question.id"
              :title="question.name"
              >{{ question.name }}</Option
            >
          </Select>
        </FormItem>
      </Form>
      <Form
        ref="modifyFormValidate"
        :model="modifyFormValidate"
        :rules="ruleValidate"
        :label-width="100"
        v-if="targetModal.type == '2'"
      >
        <FormItem label="是否显示" prop="targetVisibility" v-if="targetAllotTotal > 0">
          <RadioGroup v-model="modifyFormValidate.targetVisibility">
            <Radio :label="1">是</Radio>
            <Radio :label="0">否</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem
          label="分值"
          prop="ctfScore"
          v-if="!(curTarget.targetFlags && curTarget.targetFlags.length)"
        >
          <InputNumber
            :min="1"
            v-model="modifyFormValidate.ctfScore"
            placeholder="请输入分值"
          ></InputNumber>
          <span style="color:#f90">
            <Icon type="ios-information-circle-outline" />
            本题目的基础分
          </span>
        </FormItem>
        <FormItem label="记分方式" prop="scoreRule">
          <RadioGroup v-model="modifyFormValidate.scoreRule">
            <Radio :label="0">按题目分数</Radio>
            <Radio :label="1">按动态记分</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="类型" v-if="showCarType">
          <RadioGroup v-model="modifyFormValidate.type">
            <Radio :label="0">汽车类型</Radio>
            <Radio :label="1">普通类型</Radio>
          </RadioGroup>
        </FormItem>
        <Row>
          <Col span="4">
            <FormItem label="定时显示">
              <Checkbox
                v-model="modifyFormValidate.timer"
                @on-change="setTime"
                style="line-height:32px;"
              ></Checkbox>
            </FormItem>
          </Col>
          <Col span="14">
            <FormItem label="显示时间：">
              <!--:options = "timeOptions"-->
              <DatePicker
                v-model="modifyFormValidate.showTime"
                placeholder="请选择显示时间"
                type="datetime"
                style="width: 200px"
                :editable="false"
                format="yyyy-MM-dd HH:mm"
                v-if="modifyFormValidate.timer"
                @on-change="changeTime($event)"
              ></DatePicker>
              <span class="error-text" v-show="showErrorText">显示时间不得早于当前时间</span>
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Modal>
    <Modal v-model="tagsModal" title="提示信息" width="800px" :mask-closable="false" footer-hide>
      <!--<p v-for="tag in curTarget.targetTagsVOS" :key="tag.tag">{{tag.tag}}</p>-->
      <ctfTag :target="curTarget" v-if="tagsModal" :sceneInfo="sceneInfo"></ctfTag>
    </Modal>
    <Modal
      v-model="flagsModal"
      title="Flag信息"
      width="800px"
      :mask-closable="false"
      @on-ok="updateFlags"
      @on-cancel="flagsModal = false"
      :footer-hide="step === 'pre' ? false : true"
    >
      <ctfFlag
        ref="ctfFlags"
        :target="curTarget"
        v-if="flagsModal"
        :sceneInfo="sceneInfo"
        :step="step"
      ></ctfFlag>
    </Modal>
    <Modal
      v-model="targetAssignModal.show"
      :title="targetAssignModal.title"
      :loading="targetAssignModal.loading"
      width="800px"
      :mask-closable="false"
      @on-visible-change="visibleChange"
      @on-cancel="handleResetAssign()"
      @on-ok="modifyTargetAssign"
    >
      <Alert type="warning">
        <p>1、此功能只适合有环境的题目</p>
      </Alert>
      <Form
        ref="assignFormValidate"
        :model="assignFormValidate"
        :rules="assignRuleValidate"
        :label-width="56"
      >
        <FormItem label="环境" prop="networkId">
          <Select filterable v-model="assignFormValidate.networkId" placeholder="请选择环境" filterable>
            <Option v-for="item in subnetList" :value="item.id" :key="item.id" :title="item.name">{{
              item.name
            }}</Option>
          </Select>
        </FormItem>
        <FormItem label="团队" prop="teamIds">
          <Select filterable v-model="assignFormValidate.teamIds" placeholder="请选择团队" multiple filterable>
            <Option
              v-for="item in accessGroupList"
              :value="item.id"
              :key="item.id"
              :title="item.name"
              >{{ item.name }}</Option
            >
          </Select>
        </FormItem>
      </Form>
    </Modal>
  </search-table>
</template>

<script>
import SearchTable from '@/components/SearchTable/SearchTable'
import {
  queryCtfTarget,
  addAndAssignCtfQuestion,
  modifyCtfTarget,
  delCtfTarget,
  getSceneInfo,
  queryVmWithParty,
  clearTarget,
  queryCtfTargetAllot,
  modifyTargetAssign,
  queryNetworkList,
  batchModifyCtfTarget,
  ctfQuestionIncrement,
  batchUpdateQuestionFlags
} from '@/api/drill_compete'
import { getDictInfoByName } from '@/api/dict.js'
import { queryCtfList } from '@/api/question'
import { getFlagServerList, getstatusbyprjid } from '@/api/drill'
import { getaccessgrouplist } from '@/api/access_new'
import ctfTag from './ctfTag.vue'
import ctfFlag from './ctfFlag.vue'
import disRouteFun from '@/view/drill_compete/page/targetTeam/mixin'
import tableToolTip from '@/view/drill_compete/page/tableTooltip.vue'
import { format, sceneStatusEscape } from '@/libs/utils'

export default {
  name: 'scenes',
  props: [
    'step',
    'disabledAllBtn',
    'onlineMode',
    'progress',
    'configMode',
    'drillDetailProgress',
    'envType',
    'vpn'
  ],
  components: { ctfTag, tableToolTip, SearchTable, ctfFlag },
  mixins: [disRouteFun],
  data() {
    const validateScore = (rule, value, callback) => {
      // 验证分数
      if (!value) {
        callback(new Error('请输入正整数分值'))
      } else {
        if (value < 1) {
          callback(new Error('请输入正整数分值'))
        } else {
          callback()
        }
      }
    }
    const validateNum = (rule, value, callback) => {
      //验证只能填入数字
      var reg = new RegExp('^([1-9]|[1-9]\\d|100)$')
      //验证警戒值
      if (value) {
        if (!reg.test(value)) {
          callback(new Error('请输入1-100的整数'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    const validatePort = (rule, value, callback) => {
      //验证只能填入数字
      var reg = new RegExp(
        '^(([1-9]\\d{0,3})|([1-5]\\d{4})|(6[0-4]\\d{3})|(65[0-4]\\d{2})|(655[0-2]\\d)|(6553[0-5]))$'
      )
      //验证警戒值
      if (value) {
        if (!reg.test(Number(value))) {
          callback(new Error('请输入1-65535的整数'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    const validateIP = (rule, value, callback) => {
      //验证只能填入数字
      var reg = new RegExp(
        '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'
      )
      //验证警戒值
      if (value) {
        if (!reg.test(value)) {
          callback(new Error('ip格式错误'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      showErrorText: false,
      routeParams: {
        id: this.$route.query.id,
        prjid: this.$route.query.prjid
      },
      targetModal: {
        show: false,
        title: '',
        loading: true,
        type: 1 //1添加，2修改
      },
      targetAssignModal: {
        show: false,
        title: '题目切换环境',
        loading: true
      },
      pathList: [],
      //      vmlists:[],
      //      teamlists:[],
      queryTargetTeamInfo: {
        pageIndex: 1,
        pageSize: 10
      },
      queryTargetAllotInfo: {
        pageIndex: 1,
        pageSize: 10000,
        sceneId: this.$route.query.id
      },
      questionList: [],
      access: '1',
      needEnv: '1',
      formValidate: {
        sceneId: this.$route.query.id,
        ids: [],
        id: '',
        targetVisibility: 0
      },
      assignFormValidate: {
        networkId: '',
        teamIds: []
      },
      modifyFormValidate: {
        ctfScore: 0,
        id: '',
        questionId: '',
        sceneId: this.$route.query.id,
        targetVisibility: 0,
        showTime: '',
        timer: false,
        scoreRule: 0,
        type: 1
      },
      ruleValidate: {
        id: [{ required: true, message: '题目不能为空', trigger: 'change' }],
        ids: [
          { required: true, type: 'array', min: 1, message: '题目不能为空', trigger: 'change' }
        ],
        score: [{ required: true, type: 'number', message: '请输入分值', trigger: 'change' }],
        targetVisibility: [
          { required: true, type: 'number', message: '请选择', trigger: 'change' }
        ],
        ctfScore: [
          { required: true, type: 'number', message: '不能为空', trigger: 'change' },
          { validator: validateScore, trigger: 'change' }
        ]
      },
      assignRuleValidate: {
        networkId: [{ required: true, message: '环境不能为空', trigger: 'change' }],
        teamIds: [
          { required: true, type: 'array', min: 1, message: '请选择团队', trigger: 'change' }
        ]
      },
      initTargetObjData: {
        createtime: '',
        createuser: localStorage.getItem('username'),
        frequency: 0,
        id: '',
        isshow: 1,
        lastupdatetime: '',
        modifier: '',
        sceneid: '',
        targetdes: '',
        targetname: '',
        targetsubmittype: 0,
        targettype: 0,
        teamid: '',
        type: 0,
        uri: '',
        vmid: '',
        score: '0'
      },
      selectTargetTeams: [],
      querytime: {},
      targetTeamCol: [
        {
          type: 'selection',
          width: 60
        },
        {
          title: '题目显示名称',
          key: 'name',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          placement: 'top-left',
          width: 240
          //          width:100
        },
        {
          title: '是否需要环境',
          key: 'isNeedEnv',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          placement: 'top-right',
          render: (h, params) => {
            return h(
              'Tag',
              {
                props: {
                  color: params.row.isNeedEnv == '1' ? 'var(--status-yes)' : 'var(--status-no)',
                  type: 'border'
                },
                on: {
                  click: () => {
                    //this.showAddAndUpdate(params.row)
                  }
                }
              },
              params.row.isNeedEnv == '1' ? '是' : '否'
            )
          }
        },
        // {
        //   title:'镜像名称',
        //   key:'imageName',
        //   align:'center',
        //          ellipsis:true,
        // tooltip:true,
        // width:100,
        //          render:(h,params) => {
        //          	return h('span',params.row.imageName || '-')
        //          }
        //       },
        // {
        //         title:'方案名称',
        //         key:'flavorName',
        //         align:'center',
        //         ellipsis:true,
        //         tooltip:true,
        //         width:100,
        //          render:(h,params) => {
        //          	return h('span',params.row.flavorName || '-')
        //          }
        // },
        {
          title: '是否需要提交Flag',
          key: 'isNeedSubmitFlag',
          align: 'center',
          minWidth: 100,
          placement: 'top-right',
          render: (h, params) => {
            return h(
              'Tag',
              {
                props: {
                  color:
                    params.row.isNeedSubmitFlag == '1' ? 'var(--status-yes)' : 'var(--status-no)',
                  type: 'border'
                },
                on: {
                  click: () => {
                    //this.showAddAndUpdate(params.row)
                  }
                }
              },
              params.row.isNeedSubmitFlag == '1' ? '是' : '否'
            )
          }
        },
        {
          title: '验证类型',
          key: 'isFixedFileFlag',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          render: (h, params) => {
            return h('span', this.typeFilter(params.row.isFixedFileFlag))
          }
        },
        {
          title: '环境类型',
          key: 'circumstance',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          filter: (circumstance) => (circumstance === 'private' ? '独享环境' : '共享环境'),
          show: () => this.ctfVpn
        },
        {
          title: 'Flag',
          key: 'flag',
          tooltip: true,
          width: 100,
          render: (h, params) => {
            let total = params.row.targetFlags.length
            if (total > 0) {
              return h(
                'Button',
                {
                  on: {
                    click: () => {
                      if (total === 0) {
                        return
                      }
                      //	            				if(params.row.targetTagsVOS.length > 0){
                      this.curTarget = params.row
                      this.flagsModal = true
                      //	            				}
                    }
                  },
                  props: {
                    type: 'primary',
                    size: 'small',
                    disabled: this.disabledAllBtn
                  }
                },
                `Flag:${total}`
              )
            } else {
              return h('span', '无')
            }
          }

          //          render:(h, params) => {
          //            	return h(tableToolTip,{
          //            		props:{
          //            			content:params.row.flag,
          //            			width:200,
          //            			placement:"right",
          //            			triggle:'hover'
          //            		}
          //            	})
          //          }
        },
        {
          title: 'Flag路径',
          key: 'flagPath',
          tooltip: true,
          width: 100
          //          render:(h, params) => {
          //            	return h(tableToolTip,{
          //            		props:{
          //            			content:params.row.flagPath,
          //            			width:200,
          //            			placement:"right",
          //            			triggle:'hover'
          //            		}
          //            	})
          //          }
        },
        {
          title: '端口',
          key: 'port',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 60
        },
        {
          title: '是否显示',
          key: 'targetVisibility',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          placement: 'top-right',
          render: (h, params) => {
            return h(
              'Tag',
              {
                props: {
                  color:
                    params.row.targetVisibility == '1' ? 'var(--status-yes)' : 'var(--status-no)',
                  type: 'border'
                },
                on: {
                  click: () => {}
                }
              },
              params.row.targetVisibility == '1' ? '是' : '否'
            )
          }
        },
        {
          title: '定时显示时间',
          key: 'showTime',
          tooltip: true,
          placement: 'top-right'
        },
        //        {
        //          title:'外网访问端口',
        //          key:'externalPort',
        //          align:'center',
        //          ellipsis:true,
        //          tooltip:true,
        //        },
        //        {
        //          title:'外网服务端口',
        //          key:'externalServicePort',
        //          align:'center',
        //          ellipsis:true,
        //          tooltip:true,
        //        },
        //        {
        //          title:'路径',
        //          key:'flagPath',
        //          align:'center',
        //          tooltip:true,
        //        },
        {
          title: '分值',
          key: 'ctfScore',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 60
        },
        {
          title: '记分方式',
          key: 'scoreRule',
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.scoreRule == 0 ? '按题目分数' : '按动态记分')
          }
        },
        {
          title: '描述',
          key: 'description',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          width: 200
          //          render:(h, params) => {
          //            	return h(tableToolTip,{
          //            		props:{
          //            			content:params.row.description,
          //            			width:200,
          //            			placement:"right",
          //            			triggle:'hover'
          //            		}
          //            	})
          //          }
        },
        {
          title: '操作',
          key: 'action',
          width: this.onlineMode === 1 ? 210 : 180,
          opList: [
            {
              txt: '修改',
              disabled: (data) => {
                return this.disabledAllBtn
              },
              fun: this.showAddAndUpdate
            },
            {
              txt: '提示',
              disabled: () => {
                return this.disabledAllBtn
              },
              on: {
                click: (data, e) => {
                  this.curTarget = data
                  this.tagsModal = true
                }
              }
            },
            {
              txt: '切换环境',
              show: (data) => {
                return this.onlineMode === 1
              },
              disabled: (data) => {
                return this.disabledAllBtn || data.isNeedEnv != '1'
              },
              fun: (data) => {
                this.curTarget = data
                this.targetAssignModal.show = true
              }
            },
            {
              txt: '删除',
              tooltip: true,
              type: 'delete',
              title: '你确定要删除吗?',
              disabled: () => {
                return this.disabledAllBtn || !(this.step === 'pre' && this.configMode !== 1)
              },
              fun: (data) => {
                this.delTargetTeam(data.id)
              }
            }
          ]
        }
      ],
      allTargetTeamData: [],
      targetTeamData: [],
      targetTeamTotal: 0,
      targetAllotList: [],
      targetAllotTotal: 0, //靶标分配列表
      TargetId: '',
      subnetList: [],
      //      subnet:''
      sceneInfo: {},
      stMode: 0,
      allVms: [],
      questionMultiple: false,
      tagsModal: false,
      curTarget: {},
      showTime: '',
      accessGroupList: [],
      selectAll: false,
      showCarType: false,
      flagsModal: false,
      editable: true
    }
  },
  filters: {},
  computed: {
    showQuestionList() {
      let questionIds = this.allTargetTeamData.map((item) => item.questionId)
      if (questionIds.length) {
        return this.questionList.filter(
          (item) => !questionIds.includes(item.id) && item.category !== '安全运维'
        )
      } else {
        return this.questionList
      }
    },
    ctfVpn() {
      return this.onlineMode === 1 && this.vpn
    }
  },
  mounted() {
    //this.getAllSence()
    //this.getAllTargetHost();
    this.getProjectInfo()
    this.getAccessGroupList()
    if (this.step == 'mid') {
      //			this.targetTeamCol.pop();
    }
    this.getAllVmlist(true)
    getSceneInfo(this.$route.query.id).then((data) => {
      if (data.code == 1) {
        this.sceneInfo = data.data
        this.showTime = data.data.startTime
        this.timeOptions = {
          disabledDate(date) {
            let start = data.data.startTime
            let end = data.data.endTime
            return (
              date &&
              (date.valueOf() > new Date(end).getTime() ||
                date.valueOf() < new Date(start).getTime())
            )
          }
        }
        //      		this.stMode = JSON.parse(data.data.extension).stMode;
        //      		if(this.stMode == 0){
        //      			this.targetTeamCol.splice(0, 0,{
        //			            title:'排序',
        //			            key:'sequence',
        //			            align: 'center',
        //			            ellipsis:true,
        //			            width:100
        //		            });
        //      		}
      }
    })
    this.queryCtfQuestionList(1)
    this.getTargetTeamList()
    this.getAllTargetTeamList()
    this.queryTargetAllot()
    this.getIsCarChallengeConfig()
    // this.queryAllRange()
  },
  methods: {
    updateFlags() {
      let flags = this.$refs['ctfFlags'].formValidate.flagList
      batchUpdateQuestionFlags(
        this.$route.query.id,
        flags.map((flagItem) => {
          let { id, flag, score } = flagItem
          return { id, flag, score }
        })
      )
        .then(({ code, data, message }) => {
          if (code === 1) {
            this.$Message.info('修改成功')
            this.getTargetTeamList()
          } else {
            this.$Message.error(message)
          }
        })
        .catch((error) => {
          this.$Message.info('修改失败')
        })
    },

    // 是否需要展示汽车类型
    getIsCarChallengeConfig() {
      getDictInfoByName({ name: 'isCarChallengeConfig' }).then(({ code, attribute, message }) => {
        if (code == 1) {
          this.showCarType = attribute.data.value === '1'
          if (this.showCarType) {
            this.targetTeamCol.unshift({
              title: '类型',
              key: 'type',
              align: 'center',
              ellipsis: true,
              tooltip: true,
              render: (h, params) => {
                return h('span', params.row.type === 0 ? '汽车类型' : '普通类型')
              }
            })
          }
        }
      })
    },
    getCtfHiddenConfig() {
      return new Promise((resolve, reject) => {
        getDictInfoByName({ name: 'ctfHiddenConfig' }).then(({ code, attribute, message }) => {
          if (code == 1) {
            resolve(attribute.data.value === '1')
          } else {
            if (message === '没查询到数据') {
              // 该数据没有查询到时，并不需要提示错误信息
              resolve(false)
              return
            }
            this.$Message.error(message)
            resolve(true)
          }
        })
      })
    },
    initData() {
      if (this.targetModal.type == '1') {
        this.formValidate = {
          sceneId: this.$route.query.id,
          ids: [],
          id: '',
          targetVisibility: 0
        }
      } else {
        this.modifyFormValidate = {
          ctfScore: 0,
          id: '',
          questionId: '',
          sceneId: this.$route.query.id,
          targetVisibility: 0,
          showTime: this.sceneInfo.startTime,
          timer: false,
          scoreRule: 0,
          type: 1
        }
        this.showTime = this.sceneInfo.startTime
      }
    },
    getProjectInfo() {
      getstatusbyprjid(this.$route.query.prjid).then((data) => {
        if (data.code == 1) {
          this.projectInfo = data.attribute
          this.getProjectSubnet()
        }
      })
    },
    showAddAndUpdate(info) {
      // if(info.answers.length>0){
      // 	this.editable=true
      // } else{
      // 	this.editable=false
      // }
      console.log(this.editable, 'this.editablethis.editable')
      this.initData()
      //  		this.getProjectSubnet();
      this.targetModal.show = true
      if (!info) {
        this.targetModal.title = '添加题目'
        this.targetModal.type = 1
        this.needEnv =
          ([2, 3, 5].includes(this.progress) && this.onlineMode == 1) || this.envType === 0
            ? '0'
            : '1'
        this.queryCtfQuestionList(this.needEnv)
        this.access = '1'
      } else {
        this.targetModal.title = '修改题目'
        this.targetModal.type = 2
        //this.formValidate = {};
        //  			this.oldFormValidate = JSON.parse(JSON.stringify(info));
        this.curTarget = info
        this.modifyFormValidate = {
          sceneId: this.$route.query.id,
          id: info.id,
          questionId: info.chaId,
          ctfScore: info.ctfScore,
          scoreRule: info.scoreRule || 0,
          type: info.type === undefined ? 1 : info.type,
          targetVisibility: info.targetVisibility,
          showTime: info.showTime,
          timer: info.showTime ? true : false
        }
        this.showTime = info.showTime
      }
    },
    addTargetTeam() {
      let isNeedEnv = this.needEnv
      let list = this.showQuestionList
      let ctfQuestions = this.formValidate.ids.map((item) => {
        for (let i = 0, length = list.length; i < length; i++) {
          let question = list[i]
          if (item === question.id) {
            return {
              category: question.category,
              chaId: question.id,
              flagPath: question.flagPath,
              isFixedFileFlag: question.isFixedFileFlag,
              name: question.name,
              score: question.score,
              imageId: question.imageId,
              flavorRef: question.flavorRef,
              isNeedEnv,
              targetVisibility: 0
            }
          }
        }
      })
      addAndAssignCtfQuestion(this.routeParams.id, ctfQuestions)
        .then(({ code, message, data }) => {
          if (code === 1) {
            this.getAllTargetTeamList()
            // 添加成功后清空搜索条件，回退到首页
            this.queryTargetTeamInfo.pageIndex = 1
            this.queryTargetTeamInfo.isFixedFileFlag = ''
            this.queryTargetTeamInfo.isNeedEnv = ''
            this.queryTargetTeamInfo.isNeedSubmitFlag = ''
            this.queryTargetTeamInfo.name = ''
            this.selectAll = false
            this.getTargetTeamList()
            this.handleReset('formValidate')
            this.targetModal.show = false
            if (this.needEnv == '1') {
              // 添加有环境的题目，需要调用接口生成TOPO
              let list = ctfQuestions.map((item) => {
                return {
                  flavorRef: item.flavorRef,
                  imageRef: item.imageId,
                  name: item.name
                }
              })
              if (data) {
                let progress = sceneStatusEscape(this.progress)
                ctfQuestionIncrement(this.routeParams.id, list, {
                  competitionStatus: progress
                }).then((res) => {
                  if (res.code !== 1) {
                    this.$Message.warning(res.message)
                  } else {
                    this.$Message.success('题目添加成功，增量部署中...')
                    this.$router.push('/ctfContest')
                  }
                })
              } else {
                this.$Message.info('操作成功')
              }
            } else {
              this.$emit('getTargetTeamList')
              this.$Message.info('操作成功')
            }
          } else {
            this.$Message.warning(message)
            this.cancelLoading('targetModal')
          }
        })
        .catch((error) => {
          this.$Message.error('添加异常')
          this.cancelLoading('targetModal')
        })
    },
    async modifyTargetTeamTip() {
      let ctfHiddenConfig
      await this.getCtfHiddenConfig().then((res) => {
        ctfHiddenConfig = res
      })
      let curTargetAllots = this.targetAllotList.filter(
        (target) => target.questionId == this.curTarget.questionId
      )
      if (
        curTargetAllots.length > 0 &&
        curTargetAllots[0].vmId &&
        this.modifyFormValidate.targetVisibility != this.curTarget.targetVisibility &&
        !ctfHiddenConfig
      ) {
        // 未隐藏的情况下，需要下发规则
        if (this.modifyFormValidate.targetVisibility == 1 && this.onlineMode == 0) {
          //					let code = this.showSingle;
          let ip = curTargetAllots[0].url.split(':')[0]
          let ipLast = ip.split('.').pop()
          let port = this.curTarget.port
          //					let showSingle = `#!/bin/vbash
          //						source /opt/vyatta/etc/functions/script-template
          //						configure
          //						firewall=firewall01
          //						set firewall name $firewall rule ${Number(ipLast)+80} action accept
          //						set firewall name $firewall rule ${Number(ipLast)+80} destination address ${ip}/32
          //						commit
          //						save`
          //				    ;
          let showSingle = `
						#!/bin/vbash
						source /opt/vyatta/etc/functions/script-template
						configure
						firewall=firewall01
						set firewall name $firewall rule ${Number(ipLast) + 80} action accept
						set firewall name $firewall rule ${Number(ipLast) + 80} destination address ${ip}/32
						set firewall name $firewall rule ${Number(ipLast) + 80} protocol tcp
						set firewall name $firewall rule ${Number(ipLast) + 80} destination port ${port}
						commit
						save`
          this.getSelHxRouterVms(showSingle, `ctf显示[${this.curTarget.name}]题目`)
            .then((data) => {
              this.modifyTargetTeam()
            })
            .then((data) => {
              this.cancelLoading('targetModal')
            })
            .catch((error) => {
              this.cancelLoading('targetModal')
            })
        } else if (this.modifyFormValidate.targetVisibility == 0 && this.onlineMode == 0) {
          let ip = curTargetAllots[0].url.split(':')[0]
          let ipLast = ip.split('.').pop()
          let code = `#!/bin/vbash
						source /opt/vyatta/etc/functions/script-template
						configure
						firewall=firewall01
						del firewall name $firewall rule ${Number(ipLast) + 80}
						commit
						save
				    `
          this.getSelHxRouterVms(code, `ctf隐藏[${this.curTarget.name}]题目`)
            .then((data) => {
              this.modifyTargetTeam()
            })
            .then((data) => {
              this.cancelLoading('targetModal')
            })
            .catch((error) => {
              this.cancelLoading('targetModal')
            })
        } else {
          this.modifyTargetTeam()
        }
      } else {
        this.modifyTargetTeam()
      }
    },
    modifyTargetTeam() {
      if (!this.modifyFormValidate.id || this.showErrorText) {
        // 没有id时不需要后续操作
        this.cancelLoading('targetModal')
        return
      }
      let params = JSON.parse(JSON.stringify(this.modifyFormValidate))
      if (params.timer == false) {
        delete params.showTime
      } else {
        params.showTime = this.showTime
      }
      if (params.showTime) {
        params.showTime = params.showTime + ':00'
      }
      delete params.timer
      modifyCtfTarget(params)
        .then((data) => {
          if (data.code == 1) {
            this.getTargetTeamList()
            this.$Message.info('操作成功')
            this.handleReset('modifyFormValidate')
            this.targetModal.show = false
          } else {
            this.$Message.warning(data.message)
            this.cancelLoading('targetModal')
          }
        })
        .catch((error) => {
          this.$Message.error(error)
          this.cancelLoading('targetModal')
        })
    },
    saveTargetTeam() {
      if (this.targetModal.type == 1) {
        this.$refs['formValidate'].validate((valid) => {
          if (valid) {
            this.addTargetTeam()
          } else {
            this.cancelLoading('targetModal')
          }
        })
      } else {
        this.$refs['modifyFormValidate'].validate((valid) => {
          if (valid) {
            this.modifyTargetTeam()
          } else {
            this.cancelLoading('targetModal')
          }
        })
      }
    },
    getAllTargetTeamList() {
      queryCtfTarget(this.routeParams.id, {
        pageIndex: 1,
        pageSize: 2147483647
      })
        .then((data) => {
          if (data.code == 1) {
            this.allTargetTeamData = data.data.items || data.data
            this.targetTeamTotal = data.data.total
          } else {
            this.$Message.error('获取列表失败')
          }
        })
        .catch((error) => {
          this.$Message.error('获取列表失败')
        })
    },
    getTargetTeamList() {
      queryCtfTarget(this.routeParams.id, this.queryTargetTeamInfo)
        .then((data) => {
          if (data.code == 1) {
            this.targetTeamData = data.data.items || data.data
            this.targetTeamTotal = data.data.total
          } else {
            this.$Message.error('获取列表失败')
          }
        })
        .catch((error) => {
          this.$Message.error('获取列表失败')
        })
    },
    delTargetTeam(id) {
      delCtfTarget(id)
        .then(({ code, message }) => {
          if (code == 1) {
            // 删除后展示当前页，当前页没有数据展示前一页
            this.queryTargetTeamInfo.pageIndex =
              this.targetTeamData.length == 1 && this.queryTargetTeamInfo.pageIndex > 1
                ? this.queryTargetTeamInfo.pageIndex - 1
                : this.queryTargetTeamInfo.pageIndex
            this.getTargetTeamList()
            this.$Message.info('删除成功')
            this.getAllTargetTeamList()
            this.$refs.searchTable.delSelectItem(id)
          } else {
            this.$Message.warning(message)
          }
        })
        .catch((error) => {
          this.$Message.error('删除异常')
        })
    },
    queryTargetAllot() {
      queryCtfTargetAllot(this.queryTargetAllotInfo)
        .then((data) => {
          if (data.code == 1) {
            this.targetAllotList = data.data.items
            this.targetAllotTotal = data.data.total
          } else {
            this.$Message.warning(data.message)
          }
        })
        .catch((error) => {
          this.$Message.error(error)
        })
    },
    cancelLoading(name) {
      this[name].loading = false
      setTimeout(() => {
        this[name].loading = true
      })
    },
    typeFilter(val) {
      let str = '未定义类型'
      switch (val) {
        case '0':
          str = '固定Flag'
          break
        case '1':
          str = '静态Flag'
          break
        case '2':
          str = 'Checker'
          break
        case '3':
          str = '提交报告'
          break
        default:
          break
      }
      return str
    },
    statusFilter(val) {
      let str = ''
      switch (val) {
        case 1:
          str = '正常/防护成功'
          break
        case 2:
          str = '被攻破'
          break
        case 3:
          str = '服务异常'
          break
        case 4:
          str = '被攻破+服务异常'
          break
        default:
          break
      }
      return str
    },
    getAllVmlist(setAll) {
      let params = {
        page: 1,
        pageSize: 10000,
        sortBy: 'name',
        order: 'asc',
        findPorts: true
      }
      queryVmWithParty(this.routeParams.prjid, params).then((data) => {
        if (data.code == 1) {
          if (setAll) {
            this.allVms = data.data.list || data.data
          } else {
            let vmlists = data.data.list || data.data
            let vm = vmlists.filter((vm) => vm.imageId == this.question.imageId)
            if (vm.length > 0) {
              this.formValidate.ip = vm[0].address[0].ips[0].ipAddress
              this.formValidate.name = vm[0].name
            }
          }
        }
      })
    },
    getTargetSize(size) {
      this.queryTargetTeamInfo.pageSize = size
      this.getTargetTeamList()
    },
    getTargetPage(page) {
      this.queryTargetTeamInfo.pageIndex = page
      this.getTargetTeamList()
    },
    handleReset() {
      //this.$refs[name].resetFields();
      //    this.addTarget = false;
      let name
      if (this.targetModal.type == '1') {
        name = 'formValidate'
      } else {
        name = 'modifyFormValidate'
      }
      this.initData()
      this.$refs[name].fields.forEach(function(e) {
        if (e.fieldValue != undefined && e.fieldValue != '') {
          e.resetField()
        }
      })
    },
    // 模态框隐藏式调用
    visibleChange(flag) {
      if (!flag) {
        this.$refs['assignFormValidate'].resetFields()
      }
    },
    handleResetAssign() {
      this.assignFormValidate = {
        networkId: '',
        teamIds: []
      }
      this.$refs['assignFormValidate'].fields.forEach(function(e) {
        if (e.fieldValue != undefined && e.fieldValue != '') {
          e.resetField()
        }
      })
    },
    queryCtfQuestionList(needEnv) {
      //查询ctf题列表-不分页--需要环境
      let obj = {
        pageIndex: 1,
        pageSize: 2147483647,
        isNeedEnv: needEnv
        //visibility:'share',
        //isNeedSubmitFlag:'1',
        //category:this.autoPro.ctfType.join(',')
      }
      let _this = this
      queryCtfList(obj).then((data) => {
        if (data.code == 1) {
          //竞赛演练不要问答题
          _this.questionList = data.data.items.filter((item) => item.matchMode !== '3')
          // if(_this.questionList.length == 0){
          // 	_this.$Message.warning('该工程下没有满足要求的虚拟机');
          // }
        } else {
          _this.$Message.warning(data.message)
        }
      })
    },
    changeNeedEnv(needEnv) {
      this.formValidate.ids = []
      this.queryCtfQuestionList(needEnv)
    },
    clearTarget() {
      clearTarget(this.routeParams.id)
        .then((data) => {
          if (data.code == 1) {
            this.getTargetTeamList()
          } else {
            this.$Message.warning(data.message)
          }
        })
        .catch((error) => {
          this.$Message.error(error)
        })
    },
    cancel() {},
    // 默认一小时后展示
    setTime(timer) {
      let timeStr = format(new Date(new Date().getTime() + 3600000))
      this.modifyFormValidate.timer = timer
      this.modifyFormValidate.showTime = timeStr
      this.showTime = timeStr
      if (!timer) {
        this.showErrorText = timer
      }
    },
    changeTime(time) {
      this.showErrorText = this.isBeforeTimestamp(time)
      this.modifyFormValidate.showTime = time
      this.showTime = time
    },
    // 判断传入的时间字符串是否在当前时间之前
    isBeforeTimestamp(dataStr) {
      return new Date(dataStr) <= new Date()
    },
    modifyTargetAssign() {
      this.$refs['assignFormValidate'].validate((valid) => {
        if (valid) {
          let data = {
            networkId: this.assignFormValidate.networkId,
            projectId: this.routeParams.prjid,
            questionId: this.curTarget.questionId,
            questionName: this.curTarget.name,
            teamIds: this.assignFormValidate.teamIds
          }
          modifyTargetAssign(this.routeParams.id, data)
            .then((data) => {
              if (data.code == 1) {
                this.$Message.info('操作成功')
                this.targetAssignModal.show = false
              } else {
                this.$Message.error(data.message)
              }
              this.cancelLoading('targetAssignModal')
            })
            .catch((error) => {
              this.$Message.info('分配失败')
              this.cancelLoading('targetAssignModal')
            })
        } else {
          this.cancelLoading('targetAssignModal')
        }
      })
    },
    getProjectSubnet() {
      queryNetworkList(this.$route.query.prjid, this.projectInfo.network.id).then((data) => {
        if (data.code == 1) {
          let subnetList = []
          data.attribute.editorStage.childs.forEach((item) => {
            // 查询子网络列表
            subnetList = subnetList.concat(item.childs.filter((item) => item.dataType === 'NW'))
          })
          this.subnetList = subnetList
        }
      })
    },
    getAccessGroupList() {
      if (!this.routeParams.id) {
        return
      }
      let params = {
        pageIndex: 1,
        pageSize: 2147483647,
        testId: this.routeParams.id
      }
      this.selectGroupList = []
      getaccessgrouplist(params).then((data) => {
        if (data.code == 1) {
          this.accessGroupList = data.data.items
        } else if (data.code == -2) {
          this.accessGroupList = []
        } else {
          this.$Message.warning(data.message)
        }
      })
    },
    handleCheckAll(e) {
      this.selectAll = e
      this.targetTeamData.forEach((target) => {
        this.selectSingle(e, target)
      })
    },
    selectSingle(e, target) {
      if (target.targetVisibility == 0) {
        this.$set(target, '_checked', e)
      }
      if (
        this.targetTeamData
          .filter((target) => target.targetVisibility == 0)
          .every((target) => target._checked === true)
      ) {
        this.selectAll = true
      } else {
        this.selectAll = false
      }
    },
    disBatchShowBtn() {
      return this.selectTargetTeams.length === 0
    },
    async batchShow() {
      let data = this.selectTargetTeams.map((target) => {
        return {
          id: target.id,
          targetVisibility: 1
        }
      })
      batchModifyCtfTarget(this.$route.query.id, data)
        .then((data) => {
          if (data.code == 1) {
            this.$Message.info('操作成功')
            this.getTargetTeamList()
            this.selectTargetTeams = []
          } else {
            this.$Message.error(data.message)
          }
        })
        .catch((error) => {
          this.$Message.error('修改显示状态失败')
        })
    },
    disSelectAll() {
      return this.targetTeamData.every((target) => target.targetVisibility == 1)
    },
    showTarget(target) {
      return new Promise((resolve, reject) => {
        let curTargetAllots = this.targetAllotList.filter(
          (item) => item.questionId == target.questionId
        )
        if (curTargetAllots.length > 0 && curTargetAllots[0].vmId) {
          let ip = curTargetAllots[0].url.split(':')[0]
          let ipLast = ip.split('.').pop()
          let port = target.port
          let showSingle = `
						#!/bin/vbash
						source /opt/vyatta/etc/functions/script-template
						configure
						firewall=firewall01
						set firewall name $firewall rule ${Number(ipLast) + 80} action accept
						set firewall name $firewall rule ${Number(ipLast) + 80} destination address ${ip}/32
						set firewall name $firewall rule ${Number(ipLast) + 80} protocol tcp
						set firewall name $firewall rule ${Number(ipLast) + 80} destination port ${port}
						commit
						save`
          this.getSelHxRouterVms(showSingle, `ctf显示[${target.name}]题目`)
            .then((data) => {
              resolve(1)
            })
            .then((data) => {
              resolve(0)
            })
            .catch((error) => {
              resolve(0)
            })
        } else {
          resolve(1)
        }
      })
    }
  }
}
</script>

<style>
.drillsTable .ivu-poptip-body {
  text-align: left !important;
}
.scenesHeader {
  margin-bottom: 16px;
}
.drillTables {
  min-height: 300px;
}
.drillsTable.ivu-table-wrapper {
  overflow: inherit;
}
</style>
<style scoped>
.targetHeader {
  /*padding: 10px;*/
  margin: 15px 0;
}
.error-text {
  color: var(--red-color);
  display: inline-block;
}
</style>
